//
//  CLChooseTimeViewController.m
//  CarLifes
//
//  Created by yu on 2017/8/25.
//  Copyright © 2017年 jpas. All rights reserved.
//

#import "SearchTraceViewController.h"
#import "ReplayTraceViewController.h"
#import "WSDatePickerView.h"
#import "Utility.h"

@interface SearchTraceViewController ()
{
    NSDate *_startDate;
    NSDate *_endDate;
    
    NSString *_startDateStr;
    NSString *_endDateStr;
    
}

@property (nonatomic, copy) NSString *dateStr;

@property (weak, nonatomic) IBOutlet UIView *lineView;

@property (nonatomic, strong) UIButton *selectBtn;
@property (weak, nonatomic) IBOutlet UILabel *startLabel;
@property (weak, nonatomic) IBOutlet UILabel *endLabel;

@property (strong, nonatomic) IBOutletCollection(UIButton) NSArray *btns;
@property (weak, nonatomic) IBOutlet UIButton *startBtn;
@property (weak, nonatomic) IBOutlet UIButton *endBtn;

@property (weak, nonatomic) IBOutlet UIButton *searchBtn;
@property (nonatomic, strong) NSDate *startDate;

@property (nonatomic, strong) KLCPopup *popup;

@property (nonatomic, strong) WSDatePickerView *startTimeView;

@property (nonatomic, strong) WSDatePickerView *endTimeView;

@end

@implementation SearchTraceViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"轨迹查询";
    [self initConfig];
}

- (void)initConfig {
    if (@available(iOS 13.0, *)) {
        UIColor *startLabelColor = [UIColor colorWithDynamicProvider:^UIColor * _Nonnull(UITraitCollection * _Nonnull traitCollection) {
            if (traitCollection.userInterfaceStyle == UIUserInterfaceStyleLight) {
                return kTextBlackColor;
            } else {
                return kDarkTextColor;
            }
        }];
        self.endLabel.textColor = startLabelColor;
        self.startLabel.textColor = startLabelColor;
        
        [self.startBtn setTitleColor:UIColor.tertiaryLabelColor forState:UIControlStateNormal];
        [self.endBtn setTitleColor:UIColor.tertiaryLabelColor forState:UIControlStateNormal];
        
        UIColor *searchBtnColor = [UIColor colorWithDynamicProvider:^UIColor * _Nonnull(UITraitCollection * _Nonnull traitCollection) {
            if (traitCollection.userInterfaceStyle == UIUserInterfaceStyleLight) {
                return kRgb(255, 154, 21);
            } else {
                return kRgb(195, 115, 30);
            }
        }];
        [self.searchBtn setBackgroundColor:searchBtnColor];
        
        
        UIColor *searchBtnTitleColor = [UIColor colorWithDynamicProvider:^UIColor * _Nonnull(UITraitCollection * _Nonnull traitCollection) {
            if (traitCollection.userInterfaceStyle == UIUserInterfaceStyleLight) {
                return UIColor.whiteColor;
            } else {
                return kDarkTextColor;
            }
        }];
        [self.searchBtn setTitleColor:searchBtnTitleColor forState:UIControlStateNormal];
        
    } else {
        self.endLabel.textColor = kTextBlackColor;
        self.startLabel.textColor = kTextBlackColor;
        
        [self.startBtn setTitleColor:kTextGrayColor forState:UIControlStateNormal];
        [self.endBtn setTitleColor:kTextGrayColor forState:UIControlStateNormal];
        
        [self.searchBtn setBackgroundColor:kRgb(255, 154, 21)];
        [self.searchBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    }
}

- (void)setStartBtn:(UIButton *)startBtn
{
    _startBtn = startBtn;
    
    _startBtn.enabled = NO;
    
    
    if (@available(iOS 13.0, *)) {
//        UIColor *startBtnColor = [UIColor colorWithDynamicProvider:^UIColor * _Nonnull(UITraitCollection * _Nonnull traitCollection) {
//            if (traitCollection.userInterfaceStyle == UIUserInterfaceStyleLight) {
//                return kTextGrayColor;
//            } else {
//                return UIColor.secondaryLabelColor;
//            }
//        }];
//        [startBtn setTitleColor:UIColor.tertiaryLabelColor forState:UIControlStateNormal];
    } else {
        // Fallback on earlier versions
    }
    
    NSDate *date = [NSDate date];
    NSString *startTimeStr = [self setBtnTitleWithFormatter:@"yyyy-MM-dd" date:date];
    NSString *endTimeStr = [self setBtnTitleWithFormatter:@"yyyy-MM-dd HH:mm" date:date];
    
    [self.startBtn setTitle:NSStringFormat(@"%@ 00:00",startTimeStr) forState:UIControlStateNormal];
    [self.endBtn setTitle:NSStringFormat(@"%@",endTimeStr) forState:UIControlStateNormal];
    
    _startDateStr = startTimeStr;
    _endDateStr = endTimeStr;
    
    _startDate = [Utility stringToDateFromFormat:@"yyyy-MM-dd" timeStr:startTimeStr];
    _endDate = [Utility stringToDateFromFormat:@"yyyy-MM-dd HH:mm" timeStr:endTimeStr];
}

- (void)setEndBtn:(UIButton *)endBtn
{
    _endBtn = endBtn;
    _endBtn.enabled = NO;
}

- (IBAction)startAction:(id)sender {
    
    self.startTimeView = [[WSDatePickerView alloc] initWithDateStyle:DateStyleShowYearMonthDayHourMinute completeBlock:^(NSDate *selectTime) {
        
        if ([selectTime isLaterThanDate:_endDate]) {
            [self showAlert:@"开始时间不能晚于结束时间！"];
            return;
        }
        if ([selectTime isEqualToDate:_endDate]) {
            [self showAlert:@"开始时间不能和结束时间相同！"];
            return;
        }
////        PPLog(@"距离:%ld天",[selectTime distanceInDaysToDate:_endDate]);
//        if ([selectTime distanceInDaysToDate:_endDate] > 3) {
//            [self showAlertMessage:@"请搜索三天范围内的历史轨迹"];
//            return;
//        }
        
        NSString *startTimeStr = [selectTime stringWithFormat:@"yyyy-MM-dd HH:mm"];
        
        _startDate = selectTime;
        
        [self.startBtn setTitle:startTimeStr forState:UIControlStateNormal];

        [self.popup dismiss:YES];
        PPLog(@"start date---->\n%@\n%@",self.startBtn.currentTitle,startTimeStr);
        
    } cancelBlock:^{
        [self.popup dismiss:YES];
    }];
    self.startTimeView.doneButtonColor = [UIColor orangeColor];
    [self showPickerView:self.startTimeView];
}

- (IBAction)endAction:(id)sender {
    
    self.endTimeView = [[WSDatePickerView alloc] initWithDateStyle:DateStyleShowYearMonthDayHourMinute completeBlock:^(NSDate *selectTime) {
        
        if ([selectTime isEarlierThanDate:_startDate]) {
            [self showAlert:@"结束时间不能早于开始时间！"];
            return;
        }
        if ([selectTime isEqualToDate:_startDate]) {
            [self showAlert:@"结束时间不能和开始时间相同！"];
            return;
        }
//        if ([selectTime distanceInDaysToDate:_startDate] > 3) {
//            [self showAlertMessage:@"请搜索三天范围内的历史轨迹"];
//            return;
//        }
        
        NSString *endTimeStr = [selectTime stringWithFormat:@"yyyy-MM-dd HH:mm"];
        
        _endDate = selectTime;
        
        [self.endBtn setTitle:endTimeStr forState:UIControlStateNormal];
        [self.popup dismiss:YES];
        PPLog(@"end date---->%@",self.endBtn.currentTitle);
    } cancelBlock:^{
        [self.popup dismiss:YES];
    }];
    self.endTimeView.dateLabelColor = kBaseColor;
    [self showPickerView:self.endTimeView];
}

- (void)showPickerView:(WSDatePickerView *)pickerView
{
    [self setupPopupView:pickerView];
    [self.popup showWithLayout:KLCPopupLayoutMake(KLCPopupHorizontalLayoutCenter, KLCPopupVerticalLayoutBottom)];
}

// 展示多个view 此处必须每次重新创建content view
- (void)setupPopupView:(WSDatePickerView *)pickerView
{
    self.popup = [KLCPopup popupWithContentView:pickerView
                                       showType:KLCPopupShowTypeSlideInFromBottom
                                    dismissType:KLCPopupDismissTypeSlideOutToBottom
                                       maskType:KLCPopupMaskTypeDimmed
                       dismissOnBackgroundTouch:YES
                          dismissOnContentTouch:NO];

}

- (void)showAlert:(NSString *)message
{
    [[[UIAlertView alloc] initWithTitle:nil message:message delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];
}

- (void)setBtns:(NSArray *)btns
{
    _btns = btns;
    for (int i = 0; i < btns.count; i++) {
        UIButton *btn = btns[i];
        if (@available(iOS 13.0, *)) {
            UIColor *titleColor = [UIColor colorWithDynamicProvider:^UIColor * _Nonnull(UITraitCollection * _Nonnull traitCollection) {
                if (traitCollection.userInterfaceStyle == UIUserInterfaceStyleLight) {
                    return kTextBlackColor;
                } else {
                    return UIColor.secondaryLabelColor;
                }
            }];
            
            [btn setTitleColor:titleColor forState:UIControlStateNormal];
        } else {
            [btn setTitleColor:kTextBlackColor forState:UIControlStateNormal];
        }
        [btn setTitleColor:kBaseColor forState:UIControlStateSelected];
        
        if (btn.tag == 1) {
            btn.selected = YES;
            self.selectBtn = btn;
        }
    }
}

- (NSString *)setBtnTitleWithFormatter:(NSString *)formatter date:(NSDate *)date
{
    return [Utility dateToStringFromFormat:formatter withDate:date];
}

- (IBAction)btnsAction:(UIButton *)btn {
    
    if (btn != self.selectBtn)
    {
        self.selectBtn.selected = NO;
        btn.selected = YES;
        self.selectBtn = btn;
    }
    else
    {
        self.selectBtn.selected = YES;
    }
    
    switch (btn.tag) {
        case 1:
        {
            _startBtn.enabled = NO;
            _endBtn.enabled = NO;
            if (@available(iOS 13.0, *)) {
                [_startBtn setTitleColor:UIColor.tertiaryLabelColor forState:UIControlStateNormal];
                [_endBtn setTitleColor:UIColor.tertiaryLabelColor forState:UIControlStateNormal];
            } else {
                [_startBtn setTitleColor:kTextGrayColor forState:UIControlStateNormal];
                [_endBtn setTitleColor:kTextGrayColor forState:UIControlStateNormal];
            }
            
            NSString *startTimeStr = [self setBtnTitleWithFormatter:@"yyyy-MM-dd" date:[NSDate date]];
            
            [self.startBtn setTitle:NSStringFormat(@"%@ 00:00",startTimeStr) forState:UIControlStateNormal];
            [self.endBtn setTitle:NSStringFormat(@"%@ 23:59",startTimeStr) forState:UIControlStateNormal];
        }
            break;
        case 2:
        {
            _startBtn.enabled = NO;
            _endBtn.enabled = NO;
            
            if (@available(iOS 13.0, *)) {
                [_startBtn setTitleColor:UIColor.tertiaryLabelColor forState:UIControlStateNormal];
                [_endBtn setTitleColor:UIColor.tertiaryLabelColor forState:UIControlStateNormal];
            } else {
                [_startBtn setTitleColor:kTextGrayColor forState:UIControlStateNormal];
                [_endBtn setTitleColor:kTextGrayColor forState:UIControlStateNormal];
            }
            
            NSDate *lastDay = [NSDate dateWithTimeInterval:-24*60*60 sinceDate:[NSDate date]];
            // 昨天(年-月-日)
            NSString *lastDayStr = [self setBtnTitleWithFormatter:@"yyyy-MM-dd" date:lastDay];
            
            [self.startBtn setTitle:NSStringFormat(@"%@ 00:00",lastDayStr) forState:UIControlStateNormal];
            [self.endBtn setTitle:NSStringFormat(@"%@ 23:59",lastDayStr) forState:UIControlStateNormal];
        }
            break;
        case 3:
        {
            _startBtn.enabled = YES;
            _endBtn.enabled = YES;
            [_startBtn setTitleColor:kBaseColor forState:UIControlStateNormal];
            [_endBtn setTitleColor:kBaseColor forState:UIControlStateNormal];
        }
            break;
        default:
            break;
    }
    
    [UIView animateWithDuration:0.25f animations:^{
        _lineView.width_sd = btn.width_sd;
        _lineView.centerX_sd = btn.centerX_sd;
    }];
}

#pragma mark - search histoty traces -

- (IBAction)searchHistotyTraces:(id)sender {
    
    NSString *startTime = NSStringFormat(@"%@:00",self.startBtn.currentTitle);
    NSString *endTime = NSStringFormat(@"%@:00",self.endBtn.currentTitle);
    PPLog(@"start time = %@///end time = %@",startTime,endTime);
    PPLog(@"距离天数：%ld",[_startDate distanceInDaysToDate:_endDate]);
    if ([_startDate distanceInDaysToDate:_endDate] > 3)
    {
        [self showAlert:@"请搜索三天范围内的历史轨迹"];
        return;
    }
    
    [self.requestTool loadHistoryTrackByEqno:self.eqNo startTime:startTime endTime:endTime success:^(NSArray *historyArray,int status) {
        PPLog(@"history point = %ld",historyArray.count);
        if (status == 0 && historyArray.count >= 2) {// 获取轨迹成功
            ReplayTraceViewController *replay = [[ReplayTraceViewController alloc] init];
            replay.traces = historyArray;
            replay.ownerName = self.ownerName;
            [self.navigationController pushViewController:replay animated:YES];
        } else {
            [MBProgressHUD showToast:@"暂无轨迹数据"];
        }
    } failure:^(NSError *error) {
        PPLog(@"load history track error = %@",error);
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
